import Vue from 'vue';
import VueRouter from 'vue-router';
import store from '@/store';
import { Message } from 'element-ui';



Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  // 登录注册
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginRegisterView/LoginView.vue'),
  },
  {
    path: '/companyregister',
    name: 'companyregister',
    component: () => import('../views/LoginRegisterView/CompanyRegisterView.vue'),
  },
  {
    path: '/manage-login',
    name: 'manage-login',
    component: () => import('../views/LoginRegisterView/ManaLoginView.vue'),
  },
  {
    path: '/registerbyperson',
    name: 'registerbypersion',
    component: () => import('../views/LoginRegisterView/RegisterByPerson.vue')
  },
  {
    path: '/forgetpassword',
    name: 'forgetpassword',
    component: () => import('../views/LoginRegisterView/forgetPassword.vue')
  },
  // 管理员
  {
    path: '/manage-user',
    name: 'manage-user',
    component: () => import('../views/ManagerViews/userManagement/ManaUserViews.vue'),
    meta: { requiresAuthMana: true }
  },
  {
    path: '/data-overview', // 数据概览
    name: 'data-overview',
    component: () => import('../views/ManagerViews/ManaDataOverview.vue'),
    meta: { requiresAuthMana: true }
  },
  {
    path: '/manage-review', //审核管理
    name: 'manage-review',
    component: () => import('../views/ManagerViews/Review/ManaReviewViews.vue'),
    meta: { requiresAuthMana: true }
  },
  {
    path: '/manage-company',
    name: 'manage-company',
    component: () => import('../views/ManagerViews/Company/ManaComViews.vue'),
    meta: { requiresAuthMana: true }
  },
  {
    path: '/manage-position',
    name: 'manage-position',
    component: () => import('../views/ManagerViews/ManaPosViews.vue'),
    meta: { requiresAuthMana: true }
  },
  {
    path: '/manager-center',
    name: 'manager-center',
    component: () => import('../views/ManagerViews/SelfCenter/ManagerCenterView.vue'),
    meta: { requiresAuthMana: true }
  },
  {
    path: '/manage-feedback',
    name: 'manage-feedback',
    component: () => import('../views/ManagerViews/Feedback/ManaFeedbackView.vue'),
    meta: { requiresAuthMana: true }
  },
  {
    path: '/company-detail',
    name: 'company-detail',
    component: () => import('../views/ManagerViews/Company/ManaComDetail.vue'),
    meta: { requiresAuthMana: true }
  },
  {
    path: '/manager-change',
    name: 'manager-change',
    component: () => import('../views/ManagerViews/centerChange.vue'),
    meta: { requiresAuthMana: true }
  },
  // 公司
  {
    path: '/company',
    component: () => import('../components/CompanySidebar.vue'),
    meta: { requiresAuthCom: true },
    redirect: { name: "person-position-list" },
    children: [
      {
        //职位管理模块
        path: 'position-management',
        name: 'position-management',
        component: () => import('../views/CompanyViews/company-position/index.vue'),
        meta: { title: '职位管理', hidden: false },
        children: [
          {
            path: 'person-position-list',
            name: 'person-position-list',
            component: () => import('../views/CompanyViews/company-position/PersonPostList.vue'),
            meta: { title: '个人职位列表', icon: 'el-icon-document', hidden: false }
          },
          {
            path: 'admin-position-list',
            name: 'admin-position-list',
            component: () => import('../views/CompanyViews/company-position/CompanyPostList.vue'),
            meta: { title: '公司职位列表', icon: 'el-icon-document', hidden: false, require: ['BOSS', 'MANAGEMENT'] }
          },
          {
            path: 'position-detail/:id',
            name: 'position-detail',
            component: () => import('../views/CompanyViews/company-position/PositionDetailView.vue'),
            meta: { title: '职位详情', hidden: true },
            props: true
          },
          {
            path: 'job-posting',
            name: 'job-posting',
            component: () => import('../views/CompanyViews/company-position/JobPostingView.vue'),
            meta: { title: '发布岗位', icon: 'el-icon-plus', hidden: true }
          },
          {
            path: 'edit-posting/:id',
            name: 'edit-posting',
            component: () => import('../views/CompanyViews/company-position/JobPostingView.vue'),
            meta: { title: '编辑职位', hidden: true },
            props: true
          }
        ]
      },
      {
        //公司信息模块
        path: 'my-company',
        name: 'my-company',
        component: () => import('../views/CompanyViews/ComMessageView/index.vue'),
        redirect: { name: 'company-message' },
        meta: { title: '我的企业', icon: 'el-icon-s-home', hidden: false },
        children: [{
          path: 'company-message',
          name: 'company-message',
          component: () => import('../views/CompanyViews/ComMessageView/ComMessage.vue'),
          meta: { title: '企业信息', requiresAuthCom: true, icon: 'el-icon-info', hidden: false }

        },
        {
          path: 'company-employees',
          name: 'company-employees',
          component: () => import('../views/CompanyViews/ComMessageView/CompanyEmployees.vue'),
          meta: { title: '员工列表', requiresAuthCom: true, icon: 'el-icon-s-help', hidden: false }
        },
        {
          path: 'edit-company-message',
          name: 'edit-company-message',
          component: () => import('../views/CompanyViews/ComMessageView/editComMessageView.vue'),
          meta: { title: '修改公司信息', requiresAuthCom: true, icon: 'el-icon-edit', hidden: true }
        },
        ]
      },
      {//牛人推荐
        path: 'company-seeker',
        name: 'company-seeker',
        component: () => import('../views/CompanyViews/ComSeeker/ComSeekerView.vue'),
        meta: { title: '牛人推荐', icon: 'el-icon-user-solid', hidden: false }
      },
      {
        path: 'com-application-management',
        name: 'com-application-management',
        component: () => import("../views/CompanyViews/ComApplicationManagementView/index.vue"),
        redirect: { name: "unprocessed" },
        meta: { title: '投递管理', icon: 'el-icon-s-check', hidden: false },
        children: [
          {
            path: 'interested',
            name: 'interested',
            component: () => import("../views/CompanyViews/ComApplicationManagementView/InterestedApplication.vue"),
            meta: {
              requiresAuthCom: true,
              title: '感兴趣', icon: 'el-icon-star-on', hidden: false
            },
          },
          {
            path: 'already-applied',
            name: "already-applied",
            component: () => import("../views/CompanyViews/ComApplicationManagementView/alreadyApplied.vue"),
            meta: {
              requiresAuthCom: true,
              title: '已投递', icon: 'el-icon-s-promotion', hidden: false
            },
          },
          {
            path: 'interview-scheduled',
            name: "interview-scheduled",
            component: () => import("../views/CompanyViews/ComApplicationManagementView/InterviewScheduled.vue"),
            meta: {
              requiresAuthCom: true,
              title: '已面试', icon: 'el-icon-s-order', hidden: false
            },
          }
        ]
      },
      {//消息模块
        path: 'ComChat',
        name: 'company-chat',
        component: () => import('../views/CompanyViews/ComChat/ComChatView.vue'),
        meta: { title: '消息', icon: 'el-icon-chat-dot-round', hidden: false }
      },

      {
        path: 'recruiter-center',
        name: 'recruiter-center',
        component: () => import('../views/CompanyViews/PeersonCenter/RecruiterCenter.vue'),
        meta: { title: '个人中心', requiresAuthCom: true, icon: 'el-icon-user', hidden: true }
      },
      {
        path: 'account',
        name: 'account',
        component: () => import('../views/CompanyViews/PeersonCenter/account.vue'),
        meta: { title: '账号与安全中心', requiresAuthCom: true, icon: 'el-icon-user', hidden: true }
      },
    ]
  },


  // 用户
  {
    path: '/seekerHomePage',
    name: 'seekerHomePage',
    redirect: { name: 'HomePage' },
    children: [
      {
        path: '/home',
        name: 'HomePage',
        component: () => import('@/views/SeekerViews/HomePage/HomePage.vue')
      },
      {
        path: '/job',
        name: 'job',
        component: () => import('@/views/SeekerViews/JobPage/JobPage.vue')
      },
      {
        path: '/seekerCompany',
        name: 'seekerCompany',
        component: () => import('@/views/SeekerViews/CompanyPage/CompanyPage.vue')
      },
      {
        path: '/company/detail',
        name: 'seekerCompanyDetail',
        component: () => import('@/views/SeekerViews/CompanyPage/CompanyDetail/CompanyDetail.vue')
      },
      {
        path: '/chat',
        name: 'seekerChat',
        component: () => import('@/views/SeekerViews/PersonView/PersonChat/ChatView.vue')
      },
      {
        path: '/cv',
        name: 'PersonCv',
        component: () => import('@/views/SeekerViews/PersonView/PersonCv/PersonCv.vue')
      },
      {
        path: '/personal',
        name: 'PersonalCenter',
        component: () => import('@/views/SeekerViews/PersonView/PersonalCenter/PersonalCenter.vue')
      }
    ],
    component: () => import('@/views/SeekerViews/SeekerHome.vue')
  },

];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});


router.beforeEach(async (to, from, next) => {


  // 获取用户信息
  const recruiterUserInfo = store.state.recruiter.userInfo;
  const seekerUserInfo = store.state.seeker.userInfo;
  const managerUserInfo = store.state.manager.userInfo;

  // 判断登录状态
  const isRecruiterLoggedIn = !!recruiterUserInfo.userId;
  const isSeekerLoggedIn = !!seekerUserInfo.userId;
  const isManagerLoggedIn = !!managerUserInfo.userId;
  const isLoggedIn = isRecruiterLoggedIn || isSeekerLoggedIn || isManagerLoggedIn;

  // 需要认证的路由
  const requiresAuth = to.matched.some(record =>
    record.meta.requiresAuthMana ||
    record.meta.requiresAuthCom ||
    record.meta.requiresAuthSeeker
  );

  try {


    if (requiresAuth && !isLoggedIn) {
      throw new Error('请先登录')
    }

    // 当访问需要招聘者认证的路由时，初始化认证状态
    if (to.matched.some(record => record.meta.requiresAuthCom)) {
      // 调用招聘者模块的initAuth方法
      await store.dispatch('recruiter/initAuth');
    }

    if (requiresAuth && isLoggedIn) {
      // 检查管理员权限
      if (to.meta.requiresAuthMana && !isManagerLoggedIn) {
        throw new Error('权限不足，需要管理员身份');
      }

      if (to.meta.requiresAuthCom && !isRecruiterLoggedIn) {
        throw new Error('权限不足，需要企业招聘者身份');
      }

      if (to.meta.requiresAuthSeeker && !isSeekerLoggedIn) {
        throw new Error('权限不足，需要求职者身份');
      }

      // 权限验证通过
      next();
    } else {
      // 不需要权限的路由，直接放行
      next();
    }
  } catch (error) {
    Message.error(error.message || '请登录后再访问');

    // 未登录或权限不足时重定向到登录页
    next({
      path: '/login',
      replace: true,
      query: { redirect: to.fullPath }
    });
  }
});


export default router;